//
//  ABCThemeConfigFileManager.m
//  ABCAppearanceKit_Example
//
//  Created by mac on 2022/9/9.
//  Copyright © 2022 Joe. All rights reserved.
//

#import "ABCThemeConfigFileManager.h"

@interface ABCThemeConfigFileManager ()

/// 临时文件夹地址
@property (nonatomic, copy) NSString *tempDownloadDirPath;

/// 下载文件夹地址
@property (nonatomic, copy) NSString *downloadDirPath;

@end

@implementation ABCThemeConfigFileManager

// 创建临时文件夹
- (void)createTempDownloadDir {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = YES;
    BOOL isExist = [fileManager fileExistsAtPath:self.tempDownloadDirPath isDirectory:&isDirectory];
    if (!isExist) {
        NSError *error = nil;
        [fileManager createDirectoryAtPath:self.tempDownloadDirPath withIntermediateDirectories:YES attributes:nil error:&error];
        if (!error) {
            // 禁止被iCloud备份
            NSURL *pathUrl = [NSURL fileURLWithPath:self.tempDownloadDirPath isDirectory:YES];
            [pathUrl setResourceValue:@(YES) forKey:NSURLIsExcludedFromBackupKey error:nil];
        }
    }
}

// 清除所有临时文件
- (void)cleanTempDownloadFile {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = YES;
    BOOL isExist = [fileManager fileExistsAtPath:self.tempDownloadDirPath isDirectory:&isDirectory];
    if (!isExist) {
        return;
    }
    [fileManager removeItemAtPath:self.tempDownloadDirPath error:nil];
}

// 创建配置文件夹
- (void)createConfigDir {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = YES;
    BOOL isExist = [fileManager fileExistsAtPath:self.downloadDirPath isDirectory:&isDirectory];
    if (!isExist) {
        NSError *error = nil;
        [fileManager createDirectoryAtPath:self.downloadDirPath withIntermediateDirectories:YES attributes:nil error:&error];
    }
}

#pragma mark - lazy load

- (NSString *)tempDownloadDirPath {
    if (!_tempDownloadDirPath) {
        NSString *libraryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject;
        _tempDownloadDirPath = [libraryPath stringByAppendingPathComponent:@"themeManage/temp"];
    }
    return _tempDownloadDirPath;
}

- (NSString *)downloadDirPath {
    if (!_downloadDirPath) {
        NSString *libraryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject;
        _downloadDirPath = [libraryPath stringByAppendingPathComponent:@"themeManage/config"];
    }
    return _downloadDirPath;
}


@end
